package com.edou.base.token;

import javax.servlet.http.HttpSession;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.TagSupport;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.edou.base.util.UUIDUtil;

/**
 * 生成Token标签
 * @creator     admin
 * @create-time Apr 8, 2015   3:51:04 PM
 * @version 1.0
 */
public class TokenTag extends TagSupport{
	private static final long serialVersionUID = 8878527897806901369L;
	
	private Log logger = LogFactory.getLog(TokenTag.class);
	
	/** 默认文本框名称 */
	private static final String DEFAULT_NAME = "token";
	
	/** Token 文本框名称 */
	private String name;

	@Override
	public int doEndTag() throws JspException {
		try{
			String tokenVal = UUIDUtil.uuid();
			JspWriter out = this.pageContext.getOut();
			if(StringUtils.isBlank(name)){
				name = DEFAULT_NAME;
			}
			out.println("<input id=\"" + name + "\" name=\"" + name + "\" value=\"" + tokenVal + "\" type=\"hidden\" autocomplete=\"off\"/>");
			//保存到session里面
			HttpSession session = pageContext.getSession();
			session.setAttribute(name,tokenVal);
		}catch(Exception ex){
			logger.error(ex.getMessage(),ex);
		}
		
		return EVAL_PAGE;
	}

	/** Token 文本框名称 */
	public String getName() {
		return name;
	}

	/** Token 文本框名称 */
	public void setName(String name) {
		this.name = name;
	}
	
}
